from django import forms
from django.contrib.auth.models import User
from django.utils.text import slugify
from django.core.files.base import ContentFile

from . import models
from . import utils


class ImageSelectionForm(forms.Form):

    url = forms.URLField(widget=forms.URLInput(attrs={
        'type': 'text', 'placeholder': 'https://example.com/image.jpg'}))


class ImageCreateForm(forms.ModelForm):

    url = forms.URLField(required=False, label='', widget=forms.HiddenInput)
    title = forms.CharField(label='title', widget=forms.TextInput(attrs={
        'class': 'field'}))
    description = forms.CharField(required=False, label='description', widget=forms.Textarea(attrs={
        'class': 'field', 'type': 'text'}))

    class Meta:
        
        model = models.Image
        fields = ('url',)


    def clean_url(self):

        url = self.cleaned_data['url']
        valid_extensions = ['jpg', 'jpeg']
        extension = url.split('.')[-1].lower()

        if not 'jpg' in extension:
            raise forms.ValidationError('The given URL does not match valid image extensions')

        return url


class ImageUpdateForm(forms.ModelForm):
    
    url = forms.URLField(label='link', widget=forms.URLInput(attrs={
        'type': 'text'}))

    class Meta:

        model = models.Image
        fields = ('title', 'url', 'description')
